﻿using SignalBox.Core.Model.Timetable;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace SignalBoxEditor.UI
{
    public partial class frmTimetable : Form
    {

        private Timetable _timetable;

        public frmTimetable(Timetable tt)
        {
            InitializeComponent();

            _timetable = tt;
            bindTimetable.DataSource = _timetable;
            trainTypeBindingSource.DataSource = _timetable.TrainTypes;
            trainScheduleBindingSource.DataSource = _timetable.TrainSchedules;
            textBox1.Text = tt.Name;
            textBox2.Text = tt.StartTime;

            trainScheduleBindingSource.ListChanged += trainScheduleBindingSource_ListChanged;
        }

        void trainScheduleBindingSource_ListChanged(object sender, ListChangedEventArgs e)
        {
            foreach (TrainSchedule ts in _timetable.TrainSchedules)
            {
                ts.Timetable = _timetable;
            }
        }

        private void frmTimetable_Load(object sender, EventArgs e)
        {

        }

        private void dataGridView2_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            /*if (e.RowIndex == _timetable.TrainSchedules.Count) return;
            _timetable.TrainSchedules[e.RowIndex].Timetable = _timetable;*/
        }

        private void btnStops_Click(object sender, EventArgs e)
        {
            if (dataGridView2.SelectedRows.Count != 1) return;

            TrainSchedule ts = (TrainSchedule)dataGridView2.SelectedRows[0].DataBoundItem;

            frmTrainStops frm = new frmTrainStops(ts);
            frm.StartPosition = FormStartPosition.CenterParent;
            frm.ShowDialog(this);
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(_timetable.FileName))
            {
                SaveFileDialog dlg = new SaveFileDialog();
                dlg.Filter = "Signalbox Timetable (*.stt)|*.stt|All Files (*.*)|*.*";
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    _timetable.FileName = dlg.FileName;
                }
                else
                {
                    return;
                }
            }
            _timetable.Name = textBox1.Text;
            _timetable.StartTime = textBox2.Text;
            _timetable.Save();
        }
    }
}
